package com.css.apps.base.user.action;

import com.css.apps.base.common.Constants;
import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.base.org.model.SOrg;
import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.security.model.SecurityParam;
import com.css.apps.base.security.service.SecurityService;
import com.css.apps.base.user.leader.model.LeaderSecretary;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.service.UserHelper;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.ids.server.service.IdsService;
import com.css.util.*;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ModelDriven;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Date;
import java.util.List;

@SuppressWarnings("serial")
public class AddUser extends AdminAction implements ModelDriven {

	private static Log log = LogFactory.getLog(AddUser.class);
	private SUser item;
	private String orgIds;
	private String secretaryJson;

	public AddUser() {
		this.item = new SUser();
	}

	protected String adminGo() {
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(item.getLoginName()) || StringHelper.isEmpty(item.getRealName()) || StringHelper.isEmpty(orgIds)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			String userId = UuidUtil.getUuid();
			item.setUuid(userId);
			// 不能出现相同的UUID
			SUser user = QueryCache.get(SUser.class, item.getUuid());
			if (user != null) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS,
						Messages.getString("sysmgrMsg.idExist", new String[] { item.getUuid() }), item.getUuid());
				return Action.ERROR;
			}
			// 不能出现相同的登录名
			Object id = new QueryCache("select a.uuid from SUser a where a.loginName=:loginName ")
					.setParameter("loginName", item.getLoginName()).setMaxResults(1).uniqueResult();
			if (id != null) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR,
						Messages.getString("sysmgrMsg.loginnameExsit", new String[] { item.getLoginName() }));
				return Action.ERROR;
			}
			// 用户所属的所有部门id
			List<String> orgIdList = StringHelper.strToList(orgIds);
			// 将第一个部门id加入SUser表中的orgId字段
			item.setOrgId(orgIdList.get(0));
			item.setOpenFlag(Constants.YES);
			item.setDelFlag(Environment.UN_DELETE_STATE);
			item.setIssueDate(new Date());
			item.setIssueId(sUser.getUserId());
			item.setIssueName(sUser.getRealName());
			item.setEditDate(new Date());
			item.setTotalLoginCount(0);
			item.setFailedLoginCount(0);
			String password = SecurityService.getParamValue(SecurityParam.INIT_PASSWORD);
			if (StringHelper.isEmpty(password)) {
				item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode("123456")));
			} else {
				item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode(password)));
			}
			// if(item.getUserType().equals(BaseEnvironment.USERTYPE_SECURITY)){
			item.setActiveStatus("3");
			// }else{
			// item.setActiveStatus("1");
			// }
			item.setFailedLoginCount(0);
			UserHelper helper = new UserHelper();
			List<LeaderSecretary> lsList = helper.getLeaderSecretary(item.getUuid(), secretaryJson);
			tx = new TransactionCache();
			// 添加现有部门-用户关联
			for (String orgId : orgIdList) {
				SUserOrg userorg = new SUserOrg();
				userorg.setDeptId(orgId.trim());
				userorg.setUserId(item.getUuid());
				SOrg corp = getCorp(orgId);
				userorg.setOrgId(corp.getUuid());
				tx.save(userorg);
				item.getOrgList().add(orgId.trim());
			}
			tx.save(item);
			tx.save(lsList);
			tx.commit();
			tx = null;
			// 记录日志
			LogPart lp = new LogPart();
			lp.setOpObjType(SUser.class.getName());
			lp.setOpObjId(item.getUuid());
			lp.setRelObjType(SUser.class.getName());
			lp.setRelObjId(item.getUuid());
			lp.setOpType(LogConstant.LOG_TYPE_ADD);
			lp.setLogLevel(LogConstant.LOG_LEVEL_COMMON);
			lp.setLogData(Json.object2json(item));
			lp.setResult(LogConstant.RESULT_SUCCESS);
			lp.save();

			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"),
					item.getUuid());
			return Action.SUCCESS;
		} catch (Exception ex) {
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		} finally {

		}
	}

	private SOrg getCorp(String orgId) {
		if (StringHelper.isEmpty(orgId)) {
			return null;
		}
		SOrg parent = QueryCache.get(SOrg.class, orgId);
		if (IdsService.ORG_ORG_TYPE.equals(parent.getOrgType())) {
			return parent;
		} else {
			return getCorp(parent.getParentId());
		}
	}
	
	public SUser getModel() {
		return item;
	}

	public SUser getItem() {
		return item;
	}

	public void setItem(SUser item) {
		this.item = item;
	}

	public String getOrgIds() {
		return orgIds;
	}

	public void setOrgIds(String orgIds) {
		this.orgIds = orgIds;
	}

	public String getSecretaryJson() {
		return secretaryJson;
	}

	public void setSecretaryJson(String secretaryJson) {
		this.secretaryJson = secretaryJson;
	}

}
